package com.npy.reggie.config;

import com.alibaba.fastjson.JSON;
import com.npy.reggie.doman.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "WebFilter",urlPatterns = "/*")
@Slf4j
public class loginCheckFilter implements Filter {

    private final static AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        log.info("filter执行");
        log.info("{}",request.getSession().getAttribute("employee"));
        log.info("{}",request.getRequestURI());

        String[] uris ={
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/user/sendMsg",
                "/user/login"
        };

        if (check(uris,request.getRequestURI())){
            filterChain.doFilter(request,response);
            log.info("放行");
            return;
        }

        if (request.getSession().getAttribute("employee")!=null){

            log.info("登录后{}",request.getSession().getAttribute("employee"));
            BaseConText.setCurrentId((Long) request.getSession().getAttribute("employee"));
            log.info("获取id{}",BaseConText.getCurrentId() );
            filterChain.doFilter(request,response);
            return;
        }

        if (request.getSession().getAttribute("user")!=null){
            BaseConText.setCurrentId((Long) request.getSession().getAttribute("user"));
            filterChain.doFilter(request,response);
            return;
        }


        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        log.info("未登录");
    }

    private boolean check(String[] urls ,String url){
        for (String s : urls) {
            if (PATH_MATCHER.match(s,url)){
                return true;
            }
        }
        return false;
    }
}
